package etc.obu.service.impl;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import etc.obu.service.IResultHandler;
import etc.obu.service.model.CommonState;
import etc.obu.service.model.ObuDevice;
import etc.obu.service.model.ServiceStatus;

@SuppressWarnings("all")
public class ScanBroadcastReceiver extends BroadcastReceiver {
    private String tag = ScanBroadcastReceiver.class.getName();
    private ObuDevice targetObu;
    private IResultHandler resultHandler;
    private CommonState state;

    public ScanBroadcastReceiver(IResultHandler resultHandler) {
        this.resultHandler = resultHandler;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
            Bundle bundle = intent.getExtras();
            assert bundle != null;
            BluetoothDevice device = (BluetoothDevice) bundle.get(BluetoothDevice.EXTRA_DEVICE);
            assert device != null;
            String deviceName = device.getName();
            if (deviceName != null && deviceName.matches("^.*-OBU-.*$")) {
                if(targetObu==null){
                    targetObu=new ObuDevice(device,(Short) bundle.get(BluetoothDevice.EXTRA_RSSI));
                }else if(targetObu!=null){
                    if(targetObu.getRssi()<(Integer)bundle.get(BluetoothDevice.EXTRA_RSSI)){
                        targetObu=new ObuDevice(device,(Short) bundle.get(BluetoothDevice.EXTRA_RSSI));
                    }
                }
                Log.i(tag, device.getName());
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) {
            if (targetObu == null) {
                resultHandler.onInitialize(ServiceStatus.fail("未扫描到obu设备"));
                state=CommonState.error;
            }else{
                resultHandler.onInitialize(ServiceStatus.success("找到目标设备 ---> "+targetObu.getBluetoothDevice().getName(),targetObu));
                state=CommonState.finish;
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(intent.getAction())) {
            targetObu = null;
            state=null;
        }
    }

    public ObuDevice getTargetObu() {
        return targetObu;
    }

    public CommonState getState() {
        return state;
    }

    public void setState(CommonState state) {
        this.state = state;
    }
}
